import threading
import schedule
import time
from datetime import datetime
from typing import List, Dict
from dataclasses import dataclass
from queue import Queue

@dataclass
class HotTopic:
    platform: str
    title: str
    description: str = ""
    heat_value: int = 0
    create_time: datetime = None
    tags: List[str] = None
    generated_content: str = None  # AI生成的文案

class HotAnalysisManager:
    def __init__(self):
        self._running = False
        self._scheduler_thread = None
        self._analysis_thread = None
        self._callbacks = []
        self._history: List[HotTopic] = []
        self._analysis_queue = Queue()
        self._platforms = {
            'douyin': True,
            'bilibili': True,
            'xiaohongshu': True
        }

    def start_analysis(self, interval_minutes: int = 30):
        """启动热点分析"""
        if self._running:
            return False

        self._running = True
        
        # 清除现有的调度
        schedule.clear()
        
        # 设置定时任务
        schedule.every(interval_minutes).minutes.do(self._fetch_hot_topics)
        
        # 启动调度器线程
        self._scheduler_thread = threading.Thread(target=self._scheduler_loop)
        self._scheduler_thread.daemon = True
        self._scheduler_thread.start()

        # 启动分析线程
        self._analysis_thread = threading.Thread(target=self._analysis_loop)
        self._analysis_thread.daemon = True
        self._analysis_thread.start()

        # 立即执行一次
        self._fetch_hot_topics()
        
        return True

    def stop_analysis(self):
        """停止热点分析"""
        self._running = False
        if self._scheduler_thread:
            self._scheduler_thread.join()
            self._scheduler_thread = None
        if self._analysis_thread:
            self._analysis_thread.join()
            self._analysis_thread = None
        schedule.clear()

    def _scheduler_loop(self):
        """调度器主循环"""
        while self._running:
            schedule.run_pending()
            time.sleep(1)

    def _analysis_loop(self):
        """分析处理主循环"""
        while self._running:
            try:
                topic = self._analysis_queue.get(timeout=1)
                self._analyze_topic(topic)
            except Queue.Empty:
                continue
            except Exception as e:
                self._notify_error(f"分析处理出错: {str(e)}")

    def _fetch_hot_topics(self):
        """获取各平台热点"""
        try:
            for platform, enabled in self._platforms.items():
                if not enabled:
                    continue
                    
                topics = self._fetch_platform_topics(platform)
                for topic in topics:
                    self._analysis_queue.put(topic)
                    
            self._notify_info("热点数据获取完成")
        except Exception as e:
            self._notify_error(f"获取热点数据失败: {str(e)}")

    def _fetch_platform_topics(self, platform: str) -> List[HotTopic]:
        """获取指定平台的热点"""
        topics = []
        try:
            if platform == 'douyin':
                topics = self._fetch_douyin_topics()
            elif platform == 'bilibili':
                topics = self._fetch_bilibili_topics()
            elif platform == 'xiaohongshu':
                topics = self._fetch_xiaohongshu_topics()
        except Exception as e:
            self._notify_error(f"获取{platform}热点失败: {str(e)}")
        
        return topics

    def _fetch_douyin_topics(self) -> List[HotTopic]:
        """获取抖音热点"""
        # TODO: 实现抖音热点获取
        return []

    def _fetch_bilibili_topics(self) -> List[HotTopic]:
        """获取B站热点"""
        # TODO: 实现B站热点获取
        return []

    def _fetch_xiaohongshu_topics(self) -> List[HotTopic]:
        """获取小红书热点"""
        # TODO: 实现小红书热点获取
        return []

    def _analyze_topic(self, topic: HotTopic):
        """分析热点话题并生成内容"""
        try:
            # TODO: 使用AI模型分析话题并生成内容
            topic.generated_content = self._generate_content(topic)
            
            # 添加到历史记录
            self._history.append(topic)
            
            # 通知更新
            self._notify_topic_analyzed(topic)
            
        except Exception as e:
            self._notify_error(f"话题分析失败: {str(e)}")

    def _generate_content(self, topic: HotTopic) -> str:
        """使用AI生成相关内容"""
        # TODO: 实现AI内容生成
        return ""

    def get_history(self, platform: str = None, start_time: datetime = None, 
                   end_time: datetime = None) -> List[HotTopic]:
        """获取历史记录"""
        filtered = self._history

        if platform:
            filtered = [t for t in filtered if t.platform == platform]
        
        if start_time:
            filtered = [t for t in filtered if t.create_time >= start_time]
            
        if end_time:
            filtered = [t for t in filtered if t.create_time <= end_time]

        return filtered

    def clear_history(self):
        """清空历史记录"""
        self._history.clear()
        self._notify_info("历史记录已清空")

    def set_platform_enabled(self, platform: str, enabled: bool):
        """设置平台启用状态"""
        if platform in self._platforms:
            self._platforms[platform] = enabled

    def register_callback(self, callback):
        """注册回调函数"""
        self._callbacks.append(callback)

    def _notify_topic_analyzed(self, topic: HotTopic):
        """通知话题分析完成"""
        for callback in self._callbacks:
            callback({
                'type': 'topic_analyzed',
                'topic': topic,
                'timestamp': datetime.now()
            })

    def _notify_info(self, message: str):
        """通知一般信息"""
        for callback in self._callbacks:
            callback({
                'type': 'info',
                'message': message,
                'timestamp': datetime.now()
            })

    def _notify_error(self, message: str):
        """通知错误信息"""
        for callback in self._callbacks:
            callback({
                'type': 'error',
                'message': message,
                'timestamp': datetime.now()
            })

    @property
    def is_running(self) -> bool:
        """是否正在运行"""
        return self._running
